<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑分类' : '新建分类'"
    width="400px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入分类名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="分类描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入分类描述（可选）"
          maxlength="200"
          show-word-limit
          :rows="3"
        />
      </el-form-item>

      <el-form-item v-if="!categoryType" label="分类类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择分类类型" style="width: 100%">
          <el-option label="待办分类" value="TODO" />
          <el-option label="收藏分类" value="COLLECT" />
        </el-select>
      </el-form-item>

      <el-form-item label="父分类" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="categoryOptions"
          placeholder="请选择父分类（可选）"
          check-strictly="true"
          clearable
          :props="{
            children: 'children',
            label: 'name',
            value: 'id'
          }"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="分类颜色" prop="color">
        <div class="color-picker-wrapper">
          <el-color-picker
            v-model="form.color"
            :predefine="predefineColors"
            show-alpha
          />
          <span class="color-text">{{ form.color || '默认蓝色' }}</span>
        </div>
      </el-form-item>

      <el-form-item label="排序序号" prop="sortNo">
        <el-input-number
          v-model="form.sortNo"
          :min="0"
          :max="9999"
          placeholder="请输入排序序号"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import type { CategoryRequest, CategoryListItem } from '@/modules/todo/api'
import { categoryApi } from '@/modules/todo/api'

interface Props {
  modelValue: boolean
  editData?: CategoryListItem | null
  categoryType?: string  // 指定分类类型，如果提供则隐藏类型选择器
  defaultParentId?: string  // 默认父分类ID
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'create', request: CategoryRequest): void
  (e: 'update', id: string, request: CategoryRequest): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 分类数据
const categories = ref<CategoryListItem[]>([])

// 分类选择器选项（排除当前正在创建的分类）
const categoryOptions = computed(() => {
  return categories.value.filter(cat => cat.type === form.type)
})

// 表单数据
const form = reactive<CategoryRequest>({
  name: '',
  description: '',
  type: props.categoryType || 'TODO',
  color: '#409eff',
  sortNo: 0,
  parentId: undefined
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择分类类型', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 预定义颜色
const predefineColors = [
  '#409eff',
  '#67c23a',
  '#e6a23c',
  '#f56c6c',
  '#909399',
  '#c71585',
  '#ff1493',
  '#00bfff',
  '#00ced1',
  '#90ee90',
  '#ffd700',
  '#ff6347'
]

// 对话框显示状态
const visible = ref(false)

// 是否为编辑模式
const isEdit = computed(() => !!props.editData)

// 监听props变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
  },
  { immediate: true }
)

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (val) {
    // 对话框打开时加载分类数据
    loadCategories()
    // 如果是编辑模式，回显数据
    if (props.editData) {
      Object.assign(form, {
        name: props.editData.name,
        description: props.editData.description || '',
        type: props.categoryType || props.editData.type,
        color: props.editData.color || '#409eff',
        sortNo: props.editData.sortNo || 0,
        parentId: props.editData.parentId || undefined
      })
    } else {
      // 新建模式：如果提供了默认父分类ID，则自动选中
      if (props.defaultParentId) {
        form.parentId = props.defaultParentId
      }
    }
  }
})

// 监听分类类型变化，重新加载分类数据
watch(() => form.type, () => {
  form.parentId = undefined // 清空父分类选择
  loadCategories()
})

// 加载分类数据
const loadCategories = async () => {
  try {
    const categoryList = await categoryApi.tree({ type: form.type })
    categories.value = categoryList
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    description: '',
    type: props.categoryType || 'TODO',
    color: '#409eff',
    sortNo: 0,
    parentId: undefined  // 重置时清空父分类
  })
  formRef.value?.clearValidate()
}

// 处理关闭
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isEdit.value && props.editData) {
      // 编辑模式
      emit('update', props.editData.id, { ...form })
    } else {
      // 新建模式
      emit('create', { ...form })
    }

  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.color-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-text {
  font-size: 14px;
  color: var(--el-text-color-regular);
}
</style>